package com.wanfajie.smsdistribute.ui.template_editor

import android.app.Activity
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.text.Editable
import android.text.TextWatcher
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import com.wanfajie.smsdistribute.R
import com.wanfajie.smsdistribute.db.bean.template.TemplateBean
import com.wanfajie.smsdistribute.db.repository.impl.PlaceholderRepositoryImpl
import com.wanfajie.smsdistribute.template.convert.impl.TemplateSpannableConverter
import com.wanfajie.smsdistribute.util.confirm
import com.wanfajie.smsdistribute.util.toast
import kotlinx.android.synthetic.main.activity_template_editor.*

class SmsTemplateEditorActivity : AppCompatActivity() {

    companion object {
        const val EXTRA_TEMPLATE_ID = "template_id"
    }

    private lateinit var mTemplateBean: TemplateBean
    private val placeholderFactory = {
        PlaceholderSpan(
                bgColor = resources.getColor(R.color.colorPrimaryDark),
                textColor = Color.WHITE
        )
    }
    private val spanConverter = TemplateSpannableConverter(placeholderFactory)

    private var mSaveItem: MenuItem? = null
    private var modified: Boolean = false
        set(v) {
            field = v
            mSaveItem?.isEnabled = v
        }
    private val mTextWatcher = object : TextWatcher {
        override fun afterTextChanged(s: Editable?) = Unit
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            modified = true
        }
    }

    private fun addPlaceHolderButton(str: String) {
        val btn = layoutInflater.inflate(R.layout.button_template_tag, tag_container, false)
        btn as Button
        btn.text = str
        btn.setOnClickListener { b ->
            et_template_content.requestFocus()
            b as Button
            et_template_content.createPlaceholder("$${b.text}", placeholderFactory)
        }
        tag_container.addView(btn)
    }

    private fun createPlaceholderButtonGroup() {
        addPlaceHolderButton(getString(R.string.person_name))
        addPlaceHolderButton(getString(R.string.tel))
        PlaceholderRepositoryImpl.queryAll(true).forEach {
            addPlaceHolderButton(it.name)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_template_editor)

        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setTitle(R.string.template_editor)

        val templateId = intent.getIntExtra(EXTRA_TEMPLATE_ID, -1)
        if (templateId != -1) {
            TemplateBean.get(templateId)?.let {
                mTemplateBean = it
                loadTemplateBean(it)
                supportActionBar?.setTitle(it.title)
            }
        }

        et_template_name.addTextChangedListener(mTextWatcher)
        et_template_content.addTextChangedListener(mTextWatcher)
        createPlaceholderButtonGroup()
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_normal_editor, menu)
        mSaveItem = menu?.findItem(R.id.save)
        return true
    }

    override fun onBackPressed() {
        if (!modified) {
            finishWithResult()
        } else {
            confirmForSave()
        }
    }

    private fun confirmForSave() {

        confirm(this, R.string.modified_but_not_saved,
                R.string.do_you_want_to_save_template, R.string.save,
                R.string.dont_save, R.string.cancel) { _, witch ->

            if (witch == DialogInterface.BUTTON_POSITIVE) {
                saveOrUpdateTemplateBean()
                toast(strId = R.string.successfully_saved)
            }

            if (witch != DialogInterface.BUTTON_NEUTRAL)
                finishWithResult()
        }
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        return when (item?.itemId) {
            R.id.save -> {
                saveOrUpdateTemplateBean()
                toast(strId = R.string.successfully_saved)
                true
            }
            android.R.id.home -> {

                if (!modified) {
                    finishWithResult()
                } else {
                    confirmForSave()
                }
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    private fun loadTemplateBean(bean: TemplateBean) {
        et_template_name.setText(bean.title)
        val spanContent = bean.convert(spanConverter)
        et_template_content.setText(spanContent)
    }

    private fun saveOrUpdateTemplateBean() {
        val title = et_template_name.text.toString()
        val content = et_template_content.text.toString()

        var contentChanged = false
        if (!::mTemplateBean.isInitialized) {
            mTemplateBean = TemplateBean(title = title, content = content)
            mTemplateBean.create()
            supportActionBar?.title = mTemplateBean.title
            contentChanged = true
        } else {
            var titleChanged = false
            if (mTemplateBean.title != title) {
                mTemplateBean.title = title
                supportActionBar?.title = title
                titleChanged = true
            }

            if (mTemplateBean.content != content) {
                mTemplateBean.content = content
                contentChanged = true
            }

            if (titleChanged || contentChanged)
                mTemplateBean.update()
        }

        if (contentChanged) {
            mTemplateBean.placeholders.clear()
            et_template_content.getPlaceholders().forEach {
                val (_, s, e) = it
                mTemplateBean.addPlaceholder(s, e)
            }
        }

        modified = false
    }

    private fun finishWithResult() {
        val resultCode: Int

        if (::mTemplateBean.isInitialized) {
            resultCode = Activity.RESULT_OK
            val data = Intent()
            data.putExtra(EXTRA_TEMPLATE_ID, mTemplateBean.id)
            setResult(resultCode, data)
        } else {
            resultCode = Activity.RESULT_CANCELED
            setResult(resultCode)
        }

        finish()
    }
}